import React, {Component} from 'react';
import {ajax, promptBox, toast} from 'nc-lightapp-front';
import {chectFormAction, setFormAttrAndValue} from '../../../../../public/functions/checkFormAction'
import './index.less'
import {saveValidate, getAppPageConfig } from 'src/hrpub/common/utils/utils';
const appcode = getAppPageConfig().appcode, pagecode = getAppPageConfig().pagecode;
class Formview extends Component{
    constructor(props) {
        super(props);
        this.state = {
            mainForm: '',
            paramObj: '',
            step: '0',
            num: 0,
            formData: {},
            info2: null
        }
    }
    componentWillMount () {
        
    }
    // 将表单模板key值改变
    setDataBeforeFormKey (props, paramObj) {
        let state = this.state
        if (state.num < 1) {
            // 改dataAfter的键名
            let template = props.meta.getMeta()
            let meta = template[paramObj['beforeForm']]
            let meta2 = template[paramObj['afterForm']]
            meta.items.map(obj => {
                obj.attrcode = obj.attrcode + '_old'
                switch (obj.attrcode) {
                    case 'creator_old':
                        obj.visible = false
                        break;
                    case 'creationtime_old':
                        obj.visible = false
                        break;
                    case 'modifier_old':
                        obj.visible = false
                        break;
                    case 'modifiedtime_old':
                        obj.visible = false
                        break;
                    default:break;
                }
            })
            meta2.items.map(obj => {
                switch (obj.attrcode) {
                    case 'creator':
                        obj.visible = false
                        break;
                    case 'creationtime':
                        obj.visible = false
                        break;
                    case 'modifier':
                        obj.visible = false
                        break;
                    case 'modifiedtime':
                        obj.visible = false
                        break;
                    default:break;
                }
            })
            props.meta.setMeta(template);
        }
        this.setState({
            num: ++this.state.num
        })
    }
    // 查询变更之前的数据
    initFormDataShow (paramObj) {
        let props = this.props
        let {form} = props
        this.setDataBeforeFormKey(props, paramObj)
        let dataObj = {
            pk_psndoc_sub: paramObj.pk_psndoc_sub,
            areaCode: paramObj.mainForm + ',' + paramObj.beforeForm  + ',' + paramObj.afterForm,
            pk_org: paramObj.pk_org,
            pageCode: paramObj.pageCode
        }
        ajax({
            url: '/nccloud/hrcm/common/QueryDataCardAction.do',
            data: dataObj,
            success: (result) => {
                if (result.success) {
                    if (!result.data) {
                        return false
                    }
                    let data = result.data
                    let values = data.data[paramObj['mainForm']].rows[0].values
                    let formData = {rows: [{values}]}
                    // debugger
                    this.setState({
                        formData,
                        mainForm: paramObj['mainForm'],
                        paramObj
                    }, function () {
                        let attrMap = data.attrMap
                        let valueMap = data.valueMap
                        setFormAttrAndValue(attrMap, valueMap, props, paramObj['mainForm'], [paramObj['mainForm'], paramObj['afterForm']]) 
                        form.setAllFormValue({[paramObj['mainForm']]: formData})
                    })
                    if (paramObj.isEdit) {
                        this.setMainFormEdit()
                    }
                }
            }
        })
    }
    // 将主表单设置为编辑态
    setMainFormEdit () {
        let {form} = this.props
        let state = this.state
        let mainForm = state.mainForm
        form.setFormStatus(mainForm, 'edit')
    }
    // 将表格的数据重置为原来的
    resetMainFormData () {
        let {form} = this.props
        let paramObj = this.state.paramObj
        form.setAllFormValue({[paramObj['mainForm']]: this.state.formData})
        form.setFormStatus(paramObj['mainForm'], 'browse')
    }
    // 修改保存接口
    editInfoToSaveOrTakeEffect () {
        let props = this.props
        let state = this.state
        let paramObj = this.state.paramObj
        let {form, json, cardPagination, pageid} = props
        if (!form.isCheckNow(paramObj['mainForm'], 'warning')) {
            return false
        }
        saveValidate(props, pageid, 'dataBase', ['dataBefore', 'dataAfter'] , 'extcard').then(() => {
            let allFormValues = form.getAllFormValue(paramObj['mainForm']).rows[0].values
            let afterFormValues = {}
            for (let key in allFormValues) {
                if (key.indexOf('_old') === -1) {
                    afterFormValues[key] = allFormValues[key]
                }
            }
            let dataObj = {
                baseParam: {step: this.state.step, pageType: 'card', info2: state.info2},
                formData: {
                    model: {
                        rows: [
                            {
                                values: afterFormValues,
                                status: '1'
                            }
                        ]
                    }
                }
            }
            ajax({
                url: '/nccloud/hrcm/make/UpdateSaveDataAction.do',
                data: dataObj,
                success: (result) => {
                    if (result.success) {
                        this.setState({
                            step: result.data.step,
                            info2: result.data.info2
                        })
                        let title = json['cm6011-000043'] // 确认继续
                        if (result.data.step === '3') {
                            form.setFormStatus(paramObj['mainForm'], 'browse')
                            this.props.setBtnVisibleAndDisable('notShowSaveAndCancel')
                            title = json['cm6011-000121'] // 确认生效
                            this.props.setCardPaginationConDis(true)
                            this.props.refreshOpreation()
                        }
                        if (result.data.step !== '99') {
                            this.saveAfterTips(result.data.msg, title)
                        } else {
                            toast({
                                color: 'success',
                                content: json['cm6011-000122'] // 生效成功
                            })
                            let id = cardPagination.getNextCardPaginationId({id: paramObj.pk_psndoc_sub})
                            if (id) {
                                cardPagination.setCardPaginationId({id: paramObj.pk_psndoc_sub, status: 3})
                                this.props.handlePageInfoChange(props, id, 1)
                                paramObj.pk_psndoc_sub = id
                                this.setState({
                                    paramObj
                                })
                            } else {
                                this.EmptyAllFormValue()
                            }
                            this.setState({
                                step: '0'
                            })
                            this.props.refreshTableList()
                        }
                    }
                },
                error: (err) => {
                    this.props.refreshOpreation()
                    toast({
                        color: 'danger',
                        content: err.message
                    })
                    throw err
                }
            })
        })
    }
    // 点击修改保存成功之后的提示
    saveAfterTips (message, title) {
        let json = this.props.json
        promptBox({
            color: 'warning',
            title: title, // 确认继续
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            beSureBtnClick: this.editInfoToSaveOrTakeEffect.bind(this),
            hasCloseBtn:false,
            cancelBtnClick: this.cancelBtnClick.bind(this)
        })
    }
    // 弹窗取消操作
    cancelBtnClick () {
        this.setState({
            step: '0'
        })
    }
    // 表单改变之后的触发函数
    onAfterEvent (props, moduleId, key, value, oldValue) {
        let paramObj = this.state.paramObj
        chectFormAction(key, paramObj['mainForm'], props, [paramObj['mainForm'], paramObj['afterForm']], appcode)
    }
    //编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data){
        if(key == 'pk_conttext'){
            let meta = this.props.meta.getMeta();
            let pk_org = this.state.paramObj.pk_org;
            meta['dataAfter'].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            this.props.meta.setMeta(meta);
        }
        return true;
    }
    // 将表单清空
    EmptyAllFormValue () {
        let {form} = this.props
        let paramObj = this.state.paramObj
        form.EmptyAllFormValue(paramObj['mainForm'])
    }
    render () {
        const {form} = this.props
        let a = this.props.meta.getMeta();
        return (
            <div className="formView">
                {
                    this.state.mainForm !== '' ? form.createForm(this.state.mainForm,{
                        expandArr: [this.state.paramObj['afterForm']], // 设置关联表单某个区域展开
                        onAfterEvent: this.onAfterEvent.bind(this),
                        onBeforeEvent: this.handleEditBefore.bind(this)
                    }) : ''
                }

            </div>
        )
    }
}
export default Formview